package com.jokins.admin.vue.gitlog.action;

import com.alibaba.fastjson2.JSON;
import com.jokins.admin.vue.gitlog.actioncontext.SaveHandleGithubWebhookDoc;
import com.jokins.admin.vue.gitlog.mapper.GitWebhookMapper;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.vue.gitlog.GitPushLogs;
import com.jokins.common.util.BusinessCode;
import com.jokins.common.util.date.DateFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class SaveHandleGithubWebhookDocAction extends BaseAction<SaveHandleGithubWebhookDoc> {

    @Autowired
    private GitWebhookMapper gitWebhookMapper;

    @Override
    protected void process(SaveHandleGithubWebhookDoc actionContext) throws BusinessException {
        try {
            Map<String, Object> payload = actionContext.getParam().getPayload();
            GitPushLogs gitPushLogs = new GitPushLogs();

            Map<String, Object> head_commit = (Map<String, Object>) payload.get("head_commit");
            Map<String, Object> repository = (Map<String, Object>) payload.get("repository");

            gitPushLogs.setCommitId((String) head_commit.get("id"));
            gitPushLogs.setMessage((String) head_commit.get("message"));
            gitPushLogs.setAuthor((String) ((Map<String, Object>) head_commit.get("author")).get("name"));
            String timeString = (String) ((Map<String, Object>) head_commit.get("author")).get("time");
            gitPushLogs.setPushTime(DateFormatter.formatISO8601Date(timeString));
            gitPushLogs.setBranchName((String) payload.get("ref"));
            gitPushLogs.setRepositoryName((String) repository.get("name"));
            gitPushLogs.setComment(JSON.toJSONString(payload));
            List<String> keywords = Arrays.asList("html", "vue", "java","Android", "ios");
            String type = keywords.stream()
                    .filter(keyword -> ((String) repository.get("name")).toLowerCase().contains(keyword.toLowerCase()))
                    .findFirst()
                    .orElse("Java");
            gitPushLogs.setRepositoryType(type);

            gitWebhookMapper.insert(gitPushLogs);
            log.info("SaveHandleGithubWebhookDocAction 处理完成");
        } catch (Exception e) {
            log.error("Error processing webhook:", e);
            throw new BusinessException("Error processing webhook:",BusinessCode.PARAM_ERROR);
        }
    }
}
